<template>
  <div>
    <div class="w-full justify-center flex">
      <AnnoSearchTable
        :tableConfig="tableConfig"
        ref="SearchTable"
      ></AnnoSearchTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { AnEntity } from "@/api/sys/model/entitysModel";
  import { getEntity, getTableData } from '@/api/sys/anno';

  import { getAnnoSearchForm, getColumns } from '@/utils/anno';
  import AnnoSearchTable from './AnnoSearchTable.vue';
  // @ts-ignore
  import { Loading } from '/@/components/Loading';
  import { useAppInject } from "@/hooks/web/useAppInject";
  interface props {
    annoClassName: string;
  }
  const $props = defineProps<props>();
  const { getIsMobile } = useAppInject();

  watch(
    () => $props.annoClassName,
    (newVal) => {
      if (newVal) {
        loadConfig(newVal);
      }
    },
    { immediate: true },
  );
  const config = reactive<Partial<AnEntity>>({});

  function loadConfig(clazz: string) {
    getEntity(clazz).then((res) => {
      Object.assign(config, res);
      nextTick(() => {
        mountSearch(res);
      });
    });
  }
  const tableConfig = reactive({});
  const SearchTable = ref<InstanceType<typeof AnnoSearchTable> | null>(null);
  function mountSearch(res: AnEntity) {
    mountTable(res);
  }

  const mountTable = (res: AnEntity) => {
    const api = getTableData(
      res.entityName!,
      res.annoTree.parentKey,
      res.annoTree.key,
      res.annoTree.displayAsTree,
    );
    const searchFormFields = getAnnoSearchForm(res.columns, getIsMobile);
    Object.assign(tableConfig, {
      tableKey: $props.annoClassName,
      pagination: {
        pageSize: 20,
      },
      api,
      size: 'small',
      rowSelection: {
        type: 'radio'
      },
      clickToRowSelect: true,
      scroll: { x: true, y: 250 },
      isTreeTable: res.annoTree.displayAsTree,
      rowKey: (row) => row,
      columns: getColumns(res.columns),
      formConfig: {
        rowProps: { gutter: 16, justify: 'start' },
        labelWidth: 100,
        showAdvancedButton: false,
        labelAlign: 'left',
        autoAdvancedLine: 50,
        schemas: searchFormFields,
        autoSubmitOnEnter: true,
      },
      useSearchForm: searchFormFields.length > 0,
      showTableSetting: true,
      bordered: true,
      handleSearchInfoFn(info) {
        return info;
      },
    });
  };
  const getAddRows = () => {
    const rows = SearchTable.value!.getSelectRowKeys();
    if (rows.length < 1) return;
    return rows;
  };
  const clearSelectedRowKeys = () => {
    SearchTable.value!.clearSelectedRowKeys();
  };
  defineExpose({ getAddRows, clearSelectedRowKeys });
</script>
<style lang="less" scoped></style>
